﻿using Ma.Bussiness.ConfigExtend;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ma.Bussiness.Public
{
    public static class LogExtend
    {
        /// <summary>
        /// 新建txt 并记录信息
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="content"></param>
        public static void CreateTxt(string content, string path = "")
        {
            StreamWriter sw = null;
            try
            {
                string fileName = $"log{DateTime.Now.ToString("yyyy年MM月dd日")}.txt";
                string totalPath = string.IsNullOrEmpty(path) ? Path.Combine(StaticField.LogPath, fileName) : path;

                if (Directory.Exists(StaticField.LogPath))
                {
                    if (File.Exists(totalPath))
                        sw = File.AppendText(totalPath);
                    else
                        sw = File.CreateText(totalPath);
                }
                else
                {
                    Directory.CreateDirectory(StaticField.LogPath);
                    sw = File.CreateText(totalPath);
                }

                sw.Write(content);
            }
            catch (Exception ex)
            {
                throw new Exception($"{typeof(LogExtend).Name}类中CreateTxt方法异常");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
            }
        }

        public static void WriteLog(string msg)
        {
            var txt = $"时间：{DateTime.Now}\r\n 异常错误：{msg}";
            CreateTxt(txt);
        }
        public static void TryCatchAction(Action action)
        {
            try
            {
                action.Invoke();
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString());
                Console.WriteLine($"异常了{ex.ToString()}");
            }
        }
    }

}
